function compConnection(varargin)
% compConnection(Connectiontypes1, Connectiontypes2) or comparison 
% (Connectiontypes1, Connectiontypes2, Connectiontypes3) displays the
% comparison of two EPSP connection types (eg. striatal to striatal vs
% spinal to spinal). The program measures single epsp properties such as
% epsp amplitude, risetime, decay time constant as well as short-term
% synaptic plasticity. This function was originally intended to be used in
% finalsummary.m for multi cell recording analysis. 
% written by Taro Kiritani, tarokiritani2008@u.northwestern.edu 11/3/2010
    
connectionComparison = figure;
celltype = [];

colorMat = [1 0 0; 0 1 0; 0 0 1];

for k  = 1:nargin
    celltype{k} = varargin{1,k}.celltype;
end

% plot the analysis of single EPSPs.
compPlot('EPSP',[4 3 1],0,varargin{1,:})
ylabel('EPSP Amplitude\newlineof Connected Pairs (mV)','interpreter','tex')
set(gca,'XTickLabel',{'CSp > CSp', 'CSt > CSp', 'CSt > CSt'})
% XTicklabel_rotate([1 2 3], 0,{'CSp > CSp', 'CSt > CSp', 'CSt > CSt'},...
%     'HorizontalAlignment','center')
hold on
% saveAxes(gca,'C:\Data\Taro\ANALYSIS\multi_rec_project\dynamics\EpspAmpBar')

compPlot('decayConstant',[4 3 7],8,varargin{1,:})
ylabel('Decay time constant (ms)')
set(gca,'XTickLabel',{'CSp > CSp', 'CSt > CSp', 'CSt > CSt'})
hold on

compPlot('rise2080',[4 3 4],8,varargin{1,:})
ylabel('20%-80% rise time (ms)')
set(gca,'XTickLabel',{'CSp > CSp', 'CSt > CSp', 'CSt > CSt'})
hold on


% plot empirical cumulative distribution of first EPSP amplitude.
subplot(432)
cdfConnection('firstEPSPamp',0,varargin{1,:})
xlabel('EPSP amplitude (mV)')
ylabel('Empirical cumulative distribution')
hl = legend(celltype,4);set(hl,'box','off')
colorPlot(gca,colorMat)
set(gca,'box','off')
title('')

% plot empirical cumulative distribution of rise time.
subplot(435)
cdfConnection('rise2080',8,varargin{1,:});
xlabel('20 - 80% rise time (ms)')
ylabel('Empirical cumulative distribution')
hlb = legend(celltype,4);set(hlb,'box','off')
colorPlot(gca,colorMat)
set(gca,'box','off')
title('')

% plot empirical cumulative distribution of decay time constant tau.
subplot(438) % To do: change the positions of panels.
cdfConnection('decayConstant',8,varargin{1,:});
xlabel('Decay time constant (ms)')
ylabel('Empirical cumulative distribution')
hla = legend(celltype,4);set(hla,'box','off')
colorPlot(gca,colorMat)
set(gca,'box','off')
title('')

% plot short-term plasticity comparison.
compPlot('EPSP_normalized',[4 3 3],8,varargin{1,:})
hll = legend(celltype,4);
set(hll,'box','off')
colorPlot(gca,colorMat)
set(gca,'box','off')
ylim([0 1.5])
xlim([0 800])
title('EPSP amplitude from baseline')
ylabel('Amplitude normalized to 1st EPSP')
xlabel('time (ms)')

compPlot('EPSP_baseline_subtracted_norm',[4 3 6],8,varargin{1,:})
hlll = legend(celltype,4);
set(hlll,'box','off')
colorPlot(gca,colorMat)
set(gca,'box','off')
xlim([0 800])
title({'EPSP amplitude'; 'from decaying baseline'})
ylabel('Amplitude normalized to 1st EPSP')
xlabel('time (ms)')

compPlot('TroughsAmp',[4 3 9],8,varargin{1,:})
ht = legend(celltype,1);
set(ht,'box','off');
colorPlot(gca,colorMat)
set(gca,'box','off')
xlim([0 200])
title({'Trough amplitude'})
xlabel('time (ms)')
ylabel('Amplitude normalized to 1st EPSP')

% To do: show a couple of represantative traces from each connection type.
subplot(4,3,10)
plot(linspace(0,1,10000),varargin{1,1}(11).YDatapost,'color',[0 0 1])
xlabel('time (ms)')
ylabel('membrane potential (mV)')

subplot(4,3,11)
plot(linspace(0,1,10000),varargin{1,2}(13).YDatapost,'color',[0 1 0]);
xlabel('time (ms)')
ylabel('membrane potential (mV)')

subplot(4,3,12)
plot(linspace(0,1,10000),varargin{1,3}(10).YDatapost,'r')
xlabel('time (ms)')
ylabel('membrane potential (mV)')

editFigExport(gcf,'C:\Data\Taro\ANALYSIS\multi_rec_project\dynamics\synapticProperties.eps',5)
saveas(gcf,'C:\Data\Taro\ANALYSIS\multi_rec_project\dynamics\synapticProperties.fig')
set(gcf,'HandleVisibility','off')

figure;
compPlot('Integral',[3 3 1],0,varargin{1,:})
title('Integral first EPSP')
ylabel('Area Under the Curve\newline(mv x ms)','interpreter','tex','HorizontalAlignment','center')
set(gca,'XTickLabel',{'CSp > CSp', 'CSt > CSp', 'CSt > CSt'})

compPlot('Integrallate',[3 3 2],0,varargin{1,:})
title('Integral last EPSP')
ylabel('Area Under the Curve\newline(mv x ms)','interpreter','tex','HorizontalAlignment','center')
set(gca,'XTickLabel',{'CSp > CSp', 'CSt > CSp', 'CSt > CSt'})
set(gcf,'HandleVisibility','off')


end

function compPlot(varargin)
% COMPPLOT(FIELDNAME, POSITION, SNTHRESHOLD, CONNECTION1, CONNECTION2..) displays the
% mean value of the field and sem on axes whose position is indicated by
% position. 

snThreshold = varargin{1,3};
numOfConnectionType = nargin - 3;

% extract values for plotting.
for k = 1:numOfConnectionType
    Connection = varargin{1,k+3};
    
    % compare single values (eg. amplitude) or vectors (eg. plasticity)
    if isvector(getfield(Connection(1),varargin{1,1}))
        fieldVal = zeros(length(Connection),length(getfield(Connection(1),varargin{1,1})));
    else
        fieldVal = zeros(length(Connection),1);
    end
    
    for m = 1:length(Connection)
        a = getfield(Connection(m),varargin{1,1});
        fieldVal(m,:) = a(1,:);
    end
    snRatio = [];
    for n = 1:length(Connection)
        snRatio(n) = getfield(Connection(n),'snRatio');
    end
    
    if ~isvector(fieldVal)
        fieldVal = fieldVal(find(snRatio> snThreshold),:);
    else
        fieldVal = fieldVal(find(snRatio> snThreshold));
    end
    
    semValue(k,:) = std(fieldVal)/sqrt(size(fieldVal,1));
    meanValue(k,:) = mean(fieldVal);
    celltype{k} = Connection(1).celltype;
end

colorMat = [0 0 1; 0 1 0; 1 0 0];
%colorMat = jet;
subplot(varargin{1,2}(1),varargin{1,2}(2),varargin{1,2}(3))
% plot single values (eg. amplitude) or vectors (eg. plasticity)
if isvector(meanValue)
    ezbarweb(meanValue, semValue, semValue, colorMat)
%     barweb(meanValue,semValue,1,[],[],[],[],colorMat,[],[])
elseif strcmp(varargin{1,1},'EPSP')
    ezbarweb(meanValue(:,1), semValue(:,1), semValue(:,1), colorMat)
%     barweb(meanValue(:,1),semValue(:,1),1,[],[],[],[],[],[],[])
else
    for n = 1:numOfConnectionType
        try
            errorbar([0 50 100 150 650],meanValue(n,:),semValue(n,:))
            hold on;
        catch % this part is a very crude, make-shift solution.. fix this if problematic.
            errorbar([50 100 150],meanValue(n,:),semValue(n,:))
            hold on;
        end
    end
end

end

function colorPlot(varargin)
% COLORPLOT(H,ColorMatrix) changes the colors of lines in H (axes). The colors are
% based on jet color map (default) or on COLORMATRIX. COLORMATRIX is a nx3 matrix
% whose rows represent rgb colors.
h = varargin{1,1};
hline = get(h,'Children');

if nargin == 1
    col = jet(64);
    colindex = 64 / (length(hline) - 1) * [1:length(hline)-1];
    colindex = [1 colindex];
    colindex = fliplr(colindex);
    for k = 1:length(hline)
        set(hline(k),'Color',col(colindex(k),:))
    end
else
    for k = 1:length(hline)
        set(hline(k),'Color',varargin{1,2}(k,:)); % may not need this for loop.
    end
end

end

function cdfConnection(varargin)
% CDFCONNECTION(FIELDNAME, SNTHRESHOLD,CONNECTION1, CONNECTION2, ..) plots cumulative
% distribution function of paramaters in CONNECTIONS.

numOfConnection = nargin - 2;
snThreshold = varargin{1,2}
for k  = 1:numOfConnection
    Connection = varargin{1,k + 2};
    
    fieldVal = zeros(length(Connection),1);
    
    for m = 1:length(Connection)
        fieldVal(m,:) = getfield(Connection(m),varargin{1,1});
    end
    
    snRatio = zeros(length(Connection),1);
    for n = 1:length(Connection)
        snRatio(n) = getfield(Connection(n),'snRatio');
    end

    fieldVal = fieldVal(find(snRatio> snThreshold));
    cdfplot(fieldVal)
    hold on;
   
    celltype{k} = Connection(1).celltype;
end

grid off

end
